﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using Chire.ChireInter.Class;
using Chire.ChireInter.Students;
using Chire.ChireInter.Wechat;
using Chire.wechat;

namespace Chire.ChireInter.Sign
{
    public class Sign_Action
    {
        public enum SignType
        {
            SignType_NoSignIn = 0,                  // 未签到
            SignType_SignIn = 1,                    // 已签到
            SignType_NoSignOut = 2,                 // 未签退
            SignType_SignOut = 3,                   // 已签退
        }

        #region 添加所有学生未签到 && 未签退信息
        public void addAllStudentSignInWithClassId(string classId,string linkid) { 
            // 1. 获取班级里的所有学生
            Student_Action studentAction = new Student_Action();
            List<Student_Model> studentList = studentAction.getAllStudentWithClassId(classId);
            // 2.设置所有人未签退
            for (int i = 0; i < studentList.Count;i++ )
            {
                Student_Model studentModel = studentList[i];
                studentNoneSignStatus(studentModel.id, studentModel.classid, SignType.SignType_NoSignIn, linkid);
                studentNoneSignStatus(studentModel.id, studentModel.classid, SignType.SignType_NoSignOut, linkid);
            }
        }
        #endregion

        #region 设置所有人未签到 & 未签退状态
        private void studentNoneSignStatus(string student_id, string class_id, SignType signType, string linkId)
        {
            // 连接数据库
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();
            string StrInsert = "";
            StrInsert = "insert into sign(student_id,class_id,sign_type,date,time,linkId) values(@student_id,@class_id,@sign_type,@date,@time,@linkId)";
            SqlCommand cmd = new SqlCommand(StrInsert, sqlcon);
            // 添加参数并且设置参数值

            // 1. 作者id
            cmd.Parameters.Add("@student_id", SqlDbType.VarChar, 50);
            cmd.Parameters["@student_id"].Value = student_id;

            cmd.Parameters.Add("@class_id", SqlDbType.VarChar, 50);
            cmd.Parameters["@class_id"].Value = class_id;

            cmd.Parameters.Add("@sign_type", SqlDbType.Int, 10);
            cmd.Parameters["@sign_type"].Value = (int)signType;

            cmd.Parameters.Add("@date", SqlDbType.VarChar, 100);
            cmd.Parameters["@date"].Value = DateTime.Now.ToShortDateString().ToString();

            cmd.Parameters.Add("@time", SqlDbType.VarChar, 100);
            cmd.Parameters["@time"].Value = DateTime.Now.ToString();

            cmd.Parameters.Add("@linkId", SqlDbType.VarChar, 100);
            cmd.Parameters["@linkId"].Value = linkId;

            // 执行插入数据的操作
            cmd.ExecuteNonQuery();
            sqlcon.Close();
        }

        #endregion

        #region 1.判断今天是否签到
        public bool signHasSignIn(string student_id, string class_id)
        {
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string dateNow = DateTime.Now.ToShortDateString().ToString();

            string strselect = "select top 1 * from [sign] where student_id = '" + student_id + "' and class_id = '" + class_id + "' and sign_type = '" + (int)SignType.SignType_SignIn + "' and [date] = '" + dateNow + "'";
            SqlCommand sqlcmd = new SqlCommand(strselect, sqlcon);
            SqlDataReader dr = sqlcmd.ExecuteReader();
            bool hasSign = false;
            if (dr.Read())
            {
                hasSign = true;
            }
            sqlcon.Close();
            return hasSign;
        }
        #endregion

        #region 2.签到方法
        public void signSignInManager(string student_id, string class_id) {
            //连接数据库
            SqlConnection sqlcon1 = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon1.Open();
            //修改数据信息
            string strSqls = "update [sign] set sign_type = '" + (int)SignType.SignType_SignIn + "',time = '"+ DateTime.Now.ToString()+"'  where student_id = '"+student_id+"' and class_id = '"+class_id+"' and date = '"+DateTime.Now.ToShortDateString().ToString()+"' and sign_type = '"+ (int)SignType.SignType_NoSignIn+"'";
            

            SqlCommand cmd = new SqlCommand(strSqls, sqlcon1);
            //添加参数并且设置参数值
            cmd.ExecuteNonQuery();
            sqlcon1.Close();
        }
        #endregion

        #region 3.判断今天是否签退
        public bool signHasSignOut(string student_id, string class_id) {
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string dateNow = DateTime.Now.ToShortDateString().ToString();

            string strselect = "select top 1 * from [sign] where student_id = '" + student_id + "' and class_id = '" + class_id + "' and sign_type = '"+(int)SignType.SignType_SignOut+"' and [date] = '" + dateNow + "'";
            SqlCommand sqlcmd = new SqlCommand(strselect, sqlcon);
            SqlDataReader dr = sqlcmd.ExecuteReader();
            bool hasSign = false;
            if (dr.Read())
            {
                hasSign = true;
            }
            sqlcon.Close();
            return hasSign;
        }
        #endregion

        #region 签退方法
        public void signSignOutManager(string student_id, string class_id) {
            //连接数据库
            SqlConnection sqlcon1 = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon1.Open();
            //修改数据信息
            string strSqls = "update [sign] set sign_type = '" + (int)SignType.SignType_SignOut + "',time = '" + DateTime.Now.ToString() + "'  where student_id = '" + student_id + "' and class_id = '" + class_id + "' and date = '" + DateTime.Now.ToShortDateString().ToString() + "' and sign_type = '" + (int)SignType.SignType_NoSignOut + "'";


            SqlCommand cmd = new SqlCommand(strSqls, sqlcon1);
            //添加参数并且设置参数值
            cmd.ExecuteNonQuery();
            sqlcon1.Close();
        }
        #endregion

        #region 进行判断地址是否合格
        public List<double> adjustAddressDistance(string openid) { 
            Wechat_Location currentLocation = getLocationWithUserOpenid(openid);
            List<Wechat_Location> locationList = getSchoolList();
            List<double> distanceList = new List<double>();
            for (int i = 0; i < locationList.Count; i++) {
                Wechat_Location wechatLocationModel = locationList[i];
                // 计算距离
               double distance = Distance(Convert.ToDouble(currentLocation.lat),Convert.ToDouble(currentLocation.lon),Convert.ToDouble(wechatLocationModel.lat),Convert.ToDouble(wechatLocationModel.lon));
               distanceList.Add(distance);
            }

            return distanceList;
        }

        private Wechat_Location getLocationWithUserOpenid(string openid) {
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string dateNow = DateTime.Now.ToShortDateString().ToString();

            string strselect = "select top 1 * from wechat_location where openid = '" + openid + "'";
            SqlCommand sqlcmd = new SqlCommand(strselect, sqlcon);
            SqlDataReader dr = sqlcmd.ExecuteReader();
            Wechat_Location wechatLocation = new Wechat_Location();
            if (dr.Read())
            {
                wechatLocation.lat= dr["lat"].ToString();
                wechatLocation.lon = dr["lon"].ToString();
            }
            sqlcon.Close();
            return wechatLocation;
        }

        private List<Wechat_Location> getSchoolList(){
             SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string strselect = "select * from school";
            //查询音乐信息
            DataTable dt = new DataTable();

            SqlDataAdapter dap = new SqlDataAdapter(strselect, sqlcon);
            dap.Fill(dt);
            int rows = dt.Rows.Count;

            List<Wechat_Location> schoolList = new List<Wechat_Location>();
            for (int i = 0; i < rows; i++)
            {
                string school = dt.Rows[i]["school"].ToString();
                string lat = dt.Rows[i]["lat"].ToString();
                string lon = dt.Rows[i]["lon"].ToString();

                Wechat_Location schoolModel = new Wechat_Location()
                {
                   school = school,
                   lat = lat,
                   lon = lon
                };
                schoolList.Add(schoolModel);
            }
            sqlcon.Close();
            return schoolList;
        }


        #endregion

        #region 计算距离
        /// <summary>
        /// 根据经纬度，计算2个点之间的距离。
        /// </summary>
        /// <param name="args"></param>
 

        public static double HaverSin(double theta)
        {
            var v = Math.Sin(theta / 2);
            return v * v;
        }


        static double EARTH_RADIUS = 6371.0;//km 地球半径 平均值，千米

        /// <summary>
        /// 给定的经度1，纬度1；经度2，纬度2. 计算2个经纬度之间的距离。
        /// </summary>
        /// <param name="lat1">经度1</param>
        /// <param name="lon1">纬度1</param>
        /// <param name="lat2">经度2</param>
        /// <param name="lon2">纬度2</param>
        /// <returns>距离（公里、千米）</returns>
        public static double Distance(double lat1,double lon1, double lat2,double lon2)
        {
            //用haversine公式计算球面两点间的距离。
            //经纬度转换成弧度
            lat1 = ConvertDegreesToRadians(lat1);
            lon1 = ConvertDegreesToRadians(lon1);
            lat2 = ConvertDegreesToRadians(lat2);
            lon2 = ConvertDegreesToRadians(lon2);

            //差值
            var vLon = Math.Abs(lon1 - lon2);
            var vLat = Math.Abs(lat1 - lat2);

            //h is the great circle distance in radians, great circle就是一个球体上的切面，它的圆心即是球心的一个周长最大的圆。
            var h = HaverSin(vLat) + Math.Cos(lat1) * Math.Cos(lat2) * HaverSin(vLon);

            var distance = 2 * EARTH_RADIUS * Math.Asin(Math.Sqrt(h));

            return distance;
        }

        /// <summary>
        /// 将角度换算为弧度。
        /// </summary>
        /// <param name="degrees">角度</param>
        /// <returns>弧度</returns>
        public static double ConvertDegreesToRadians(double degrees)
        {
            return degrees * Math.PI / 180;
        }

        public static double ConvertRadiansToDegrees(double radian)
        {
            return radian * 180.0 / Math.PI;
        }

        #endregion

        #region 获取签到班级
        public List<Sign_Class_Model> getSignClassListWithClassId(string classId)
        {   
            Class_Action classAction = new Class_Action();
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string strselect;
            if (classId.Length > 0)
            {
                strselect = "select * from sign_class where class_id = '" + classId + "'";
            }
            else {
                strselect = "select * from sign_class";
            }
           
            //查询音乐信息
            DataTable dt = new DataTable();

            SqlDataAdapter dap = new SqlDataAdapter(strselect, sqlcon);
            dap.Fill(dt);
            int rows = dt.Rows.Count;

            List<Sign_Class_Model> signClassList = new List<Sign_Class_Model>();
            for (int i = 0; i < rows; i++)
            {
                string id = dt.Rows[i]["id"].ToString();
                string date = dt.Rows[i]["date"].ToString();
                string class_id = dt.Rows[i]["class_id"].ToString();
                string linkId = dt.Rows[i]["linkId"].ToString();
                Class_Model classModel = classAction.getClassInfoWithId(class_id);
                long timeInterval = Constance.Instance.ConvertDateTimeInt(Convert.ToDateTime(date));

                Sign_Class_Model signClassModel = new Sign_Class_Model()
                {
                    id = id,
                    date = date,
                    class_id = class_id,
                    linkId = linkId,
                    classModel = classModel,
                    dateTimeInterval = timeInterval,
                };
                signClassList.Add(signClassModel);
            }
            sqlcon.Close();
            return signClassList;
        }
        #endregion

        #region 添加签到信息
        public void addSignClassInfo(string classId,string linkId) { 
              // 连接数据库
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();
            string StrInsert = "";
            StrInsert = "insert into sign_class(date,class_id,linkId) values(@date,@class_id,@linkId)";
            SqlCommand cmd = new SqlCommand(StrInsert, sqlcon);
            // 添加参数并且设置参数值

            // 1. 作者id
            cmd.Parameters.Add("@date", SqlDbType.VarChar, 50);
            cmd.Parameters["@date"].Value = DateTime.Now.ToShortDateString();

            cmd.Parameters.Add("@class_id", SqlDbType.VarChar, 50);
            cmd.Parameters["@class_id"].Value = classId;

            cmd.Parameters.Add("@linkId", SqlDbType.VarChar, 50);
            cmd.Parameters["@linkId"].Value = linkId;

            // 执行插入数据的操作
            cmd.ExecuteNonQuery();
            sqlcon.Close();
        }
        #endregion

        #region 根据linkId获取所有的签到信息
        public List<Sign_Model> getSignListWithLinkId(string linkId)
        {
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string strselect = "select * from [sign] where linkId='"+linkId+"'";
            //查询音乐信息
            DataTable dt = new DataTable();

            SqlDataAdapter dap = new SqlDataAdapter(strselect, sqlcon);
            dap.Fill(dt);
            int rows = dt.Rows.Count;

            List<Sign_Model> signList = new List<Sign_Model>();
            for (int i = 0; i < rows; i++)
            {
                string id = dt.Rows[i]["id"].ToString();
                string student_id = dt.Rows[i]["student_id"].ToString();
                string class_id = dt.Rows[i]["class_id"].ToString();
                string sign_type = dt.Rows[i]["sign_type"].ToString();
                string date = dt.Rows[i]["date"].ToString();
                string time = dt.Rows[i]["time"].ToString();
   
                Sign_Model signModel = new Sign_Model()
                {
                   id = id,
                   student_id = student_id,
                   class_id = class_id,
                   sign_type = sign_type,
                   date = date,
                   time = time,
                };
                signList.Add(signModel);
            }
            sqlcon.Close();
            return signList;
        }
        #endregion

        #region 获取今天的签到信息
        public List<Class_Model> getCurrentTodaySignClassInfoManager(string openid)
        {
            Class_Action classAction = new Class_Action();
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string dateNow = DateTime.Now.ToShortDateString().ToString();
            string strselect = "select  * from [sign] where student_id = '" + openid + "' and [date] = '" + dateNow + "' and (sign_type = '1' or sign_type = '0')";

            //查询音乐信息
            DataTable dt = new DataTable();

            SqlDataAdapter dap = new SqlDataAdapter(strselect, sqlcon);
            dap.Fill(dt);
            int rows = dt.Rows.Count;

            List<Class_Model> classList = new List<Class_Model>();
            for (int i = 0; i < rows; i++)
            {
                string class_id = dt.Rows[i]["class_id"].ToString();
                Class_Model classModel = classAction.getClassInfoWithId(class_id);
                classList.Add(classModel);
            }
            sqlcon.Close();
            return classList;
        }
        #endregion
    }
}